package com.cke.yang.common.app.handler;

import com.cke.yang.common.domain.model.SecUserDetails;
import com.cke.yang.common.infra.utils.UserDetailsUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充元数据处理器
 *
 * @author luozhaojian
 * @date 2025-10-7 11:27:00
 */
@Component
public class AutoFillMetaDataHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdAt", Date.class, new Date());
        this.strictInsertFill(metaObject, "createdBy", Long.class, getCurrentUser());
        this.strictInsertFill(metaObject, "lastUpdatedAt", Date.class, new Date());
        this.strictInsertFill(metaObject, "lastUpdatedBy", Long.class, getCurrentUser());
        this.strictInsertFill(metaObject, "objectVersionNumber", Long.class, 1L);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "lastUpdatedAt", Date.class, new Date());
        this.strictUpdateFill(metaObject, "lastUpdatedBy", Long.class, getCurrentUser());
    }


    private Long getCurrentUser() {
        SecUserDetails userDetails = UserDetailsUtils.getCurrentUserDetails();
        return userDetails == null ? null : userDetails.getUserId();
    }

}
